import re


from . import api
from flask import request, jsonify, session
from iHome import redis_store
from iHome.models import User
from iHome import db

import logging

from ..utils.secret import custom_md5

"""
注册接口
url /api/v1.0/users

请求方式: post

请求参数: 
        mobile    str   
        smscode   str
        password  str
        password2 str
请求响应:
    json
    errno: 0  注册成功

"""


@api.route("/users/", methods=['POST'])
def user_register():
    params = request

    mobile = params.json.get('mobile')
    sms_code = params.json.get('phonecode')
    password = params.json.get('password')
    password2 = params.json.get('password2')

    if not all([mobile, sms_code, password, password2]):
        return jsonify({
            'errno': 4001,
            'errmsg': '不能为空'
        })

    redis_smscode = redis_store.get('SmsCode_' + str(mobile))

    if redis_smscode is None:
        return jsonify({
            'errno': 4002,
            'errmsg': '短信验证码已过期'
        })

    if sms_code != redis_smscode.decode():
        return jsonify({
            'errno': 4002,
            'errmsg': '短信验证码错误'
        })

    redis_store.delete('SmsCode_' + str(mobile))

    if not re.match('^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$', password) or not re.match('^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$', password2):
        return jsonify({
            'errno': 4002,
            'errmsg': '密码必须包含字母数字,且在6-18位'
        })

    if password != password2:
        return jsonify({
            'errno': 4002,
            'errmsg': '两次密码不一致'
        })

    new_password = custom_md5(password)

    try:
        u = User(
            name=mobile,
            mobile=mobile,
            password_hash=new_password
        )
        db.session.add(u)
        db.session.commit()
    except Exception as e:
        print(e)

        return jsonify(errno='4002', errmsg='注册失败')

    # 保持登录状态
    session['mobile'] = mobile
    session['name'] = mobile
    session['user_id'] = u.id

    return jsonify({
        'errno': 0,
        'errmsg': '注册成功'
    })


"""
url : session
请求方式: post
参数:  手机号  密码  都必传  mobile   password
"""


@api.route("/sessions/", methods=['POST'])
def login():
    """接收参数"""
    json_dict = request

    mobile = json_dict.json.get('mobile')
    password = json_dict.json.get('password')

    """校验参数"""

    """根据手机号查找用户"""
    user = User.query.filter_by(mobile=mobile).first()
    if user is None:
        return jsonify({
            'errno': 4001,
            'errmsg':'用户不存在'
        })

    """校验密码"""
    md5_pwd = custom_md5(password)

    if user.password_hash != md5_pwd:
        return jsonify({
            'errno': 4001,
            'errmsg': '密码错误'
        })

    """保持登录状态"""
    print('----' + str(user.mobile) + str(user.name) + str(user.id) + '----')
    session['mobile'] = user.mobile
    session['name'] = user.name
    session['user_id'] = user.id

    """返回响应"""
    return jsonify({
        'errno': "0",
        'errmsg': '登录成功'
    })


@api.route("/sessions/", methods=['GET'])
def check_login():
    # name = session.get('name')
    # user_id = session.get('user_id')
    user_id = 1
    name = User.query.filter_by(id=user_id).first().name

    return jsonify({
        'errno': "0",
        'errmsg': '登录成功',
        'data':{
            'name': name,
            'user_id': user_id
        }
    })


"""
装饰器本质 :  函数嵌套函数
作用: 不改变源码的情况下,在原有的功能基础上,拓展功能
类继承: 类装饰器

"""


def swapper(*args, **kwargs):
    def center(func):
        return func(*args, **kwargs)
    return center


def sum(a, b):
    return a + b


center = swapper(1, 2)
result = center(sum)


"""退出登录"""


@api.route('/sessions/', methods=["DELETE"])
def logout():
    session.pop('name', None)
    session.pop('mobile', None)
    session.pop('user_id', None)
    return jsonify(errno="0", errmsg="OK")



